package epoch.game.core.actor;

public abstract class ATimer {
	// just for being compitable with GameTimer
	protected int timeout;
	protected int repeat;
	protected int period;
	private volatile boolean canceled;
	
	public ATimer(int period) {
		this(period, -1, period);
	}
	public ATimer(int period, int repeat) {
		this(period, repeat, period);
	}
	public ATimer(int period, int repeat, int timeout) {
		period = period/10;
		if (period <= 0) 
			period = 1;
		timeout = timeout/10;
		if (timeout <= 0) {
			timeout = 1;
		}
		this.timeout = timeout;
		this.repeat = repeat;
		this.period = period;
		this.canceled = false;
	}
	
	boolean tick() {
		if (canceled) {
			return false;
		}
		try {
			doAction();
		} catch (Throwable e) {
			Log.error(null, "ATimer doAction error: this="+this.getClass(), e);
		}
		if (repeat > 0) {
			repeat--;
		}
		if (repeat == 0) {
			return false;
		}
		if (timeout != period) {
			timeout = period;
		}
		return true;
	}
	
	protected abstract void doAction();
	
	public int timeout() {
		return timeout;
	}
	public void cancel() {
		canceled = true;	
	}
	public boolean isCanceled(){
		return canceled;
	}
}